<?php

namespace Home\Controller;
use Think\Controller;

/**
* @Function 极速版控制器
* @param type
* @autho cheng
*/
class SpeedController extends BaseController
{

    /**
     * @Desc  : 极速版入库
     * @Author：quyang
     * @Param ：
     * @Time  ：2017/5/9 9:49
     * @Update：2017/5/9
     **/
    public function speedParcelStorage()
    {

        $param  = I('param.');

        if(empty($param['stationId']) || empty($param['companyId']) || empty($param['companyName']) || $param['source'] == '' || empty($param['packetInfo'])){
            $this->param_error(false);
        }

        $pregMobile = '/^[1][34578]\d{9}$/';

        $packetInfo = rtrim( $param['packetInfo'] , ',' );

        $packetsArr = json_decode(htmlspecialchars_decode($packetInfo), true);

        $balance = D('Home/User')->where(array('f_user_id'=>$param['stationId']))->field('f_user_id,f_buy_count,f_speed_status')->find();

        //验证用户下短信余额
        if ( $balance['f_buy_count'] < count($packetsArr) ){
            $this->auto_error( '站点短信余额不足, 无法入库' );
        }

        //验证是否有极速版权限
        if ( $balance['f_speed_status'] != '1' )
        {
            $this->auto_error( '站点没有极速入库权限' );
        }

        foreach ($packetsArr as $k => $v){

            if(!preg_match($pregMobile, $v['mobile'])){
                $this->auto_error('手机号错误');
            }

            //编号不允许为空  2017-03-04
            if ( !preg_match("/^[0-9]{1,6}$/",$v['num']) ){
                $this->auto_error('请填写1-6位纯数字编号');
            }

            //获取手机号
            $mobile_data[] = $v['mobile'];

            //get参数
            $getData = I('get.');

            $packets[] = array(
                'f_station_id'          => $param['stationId'],
                'f_company_id'          => $param['companyId'],
                'f_company_name'        => $param['companyName'],
                'f_recipient_mobile'    => $v['mobile'],
                'f_recipient_name'      => empty($v['name']) ? '' : $v['name'],
                'f_frame_code'          => empty($v['frameCode']) ? '' : $v['frameCode'],
                'f_num'                 => $v['num'],
                'f_input_source'        => intval( $param['source'] ),
                'f_exp_id'              => empty( $param['fExpId'] ) ? '0' : $param['fExpId'],
                'source'                => $getData['bmxSource'],
                'version'               => $getData['bmxVersion']
            );
        }

        //验证手机号是否加入黑名单
        $Order = new \Home\Server\OrderService();
        $mobile_status = $Order->mobileStatus( $param['stationId'] , $mobile_data );

        if ( is_array( $mobile_status[0] ) )
        {
            $this->auto_error( '手机号:'.$mobile_status[0]['f_recipient_mobile'].'已被拉黑' );
        }

        //入库
        $Speed = new \Home\Server\SpeedParcelService();
        $arr = $Speed->PutStorage( $packets );

        if ( $arr['insertResult'] == false  && empty($arr['updateResult']) ) {
            $this->output(false);
        }

        $this->output(true ,array() ,'入库成功');
        
    }

    /**
     * @Desc  : 极速版短信推送
     * @Author：quyang
     * @Param ：
     * @Time  ：2017/5/9 11:16
     * @Update：2017/5/9
     **/
    public function speedSendSms( $parcelId ,$smsType = 0 )
    {


        //获取替换信息
        foreach ($parcelId as $value){

            $parcelDetail = new \Home\Server\SpeedParcelService();
            $parcelNotice = new \Home\Server\ParcelNoticeResultServer();
            $SmsLog = new \Home\Server\SmsLogServer();

            $data = $parcelDetail->getParcelDetails($value);

            //判断短信余量
            if ($data['fBuyCount'] == 0){

                $parcelNotice->updateSendNotice($data['packageCode'],null,'2','B');
                continue;
            }

            //极速版调用专业版模板
            $arr = D('Home/SmsTemplate')->getemplate( '' , 7 );

            //判断短信模板获取失败状态为D  12-22
            if(empty($arr['f_template_content'])){
                $parcelNotice->updateSendNotice($data['packageCode'],null,'2','D');
                continue;
            }
            //替换短信模板
            $autograph = C('AUTOGRAPH');
            $list = str_replace('{companyName}',$data['companyName'],$arr['f_template_content']);
            $list = str_replace(array('{address}','{extractCode}','{openTime}','{mobile}','{frameCode}'),array($data['address'],$data['extractCode'],$data['openTime'],$data['userPhone'],$data['fFrameCode'].$data['fNum']),$list);

            //如果短信模板替换失败则短信发送状态为2，错误码为E  12-22
            if(empty($list)){
                $parcelNotice->updateSendNotice($data['packageCode'],null,'2','E');
                continue;
            }

            $autograph .= $list;

            $result = send_sms($data['mobile'],$autograph);
            $patterns = "/\d+/";
            preg_match_all($patterns,$result,$msg);
            //计算短信条数
            if (mb_strlen($autograph,'utf-8')<=70){
                $smsnum = '1';
            }else{
                //超过70字，按64字每条计算
                $smsnum = ceil(mb_strlen($autograph,'utf-8')/64);
            }

            if($msg['0']['1'] == '0'){
                //更新短信内容、发送状态
                $parcelNotice->updateSendNotice($data['packageCode'],$autograph,'3','0');
                //更新短信余额
                D('Home/User')->updateSms($data['stationId'],$smsnum);
                //写入短信log
                $SmsLog->addLog( $data , $msg['0']['2'] , $msg['0']['1'] , $autograph , $smsnum , $smsType , 'JS' );
            }else{
                //短信发送失败改状态为发送失败
                $parcelNotice->updateSendNotice($data['packageCode'],$autograph,'2','C');
            }
        }
        
    }

    /**
     * @Desc  : 查询极速状态包裹(多状态包裹)
     * @Author：quyang
     * @Param ：
     * @Time  ：2017/5/9 15:08
     * @Update：2017/5/9
     **/
    public function querySpeedParcel()
    {

        $data = I('param.');

        //sendNotice为发送状态  1.发送成功  2.草稿箱
        if (empty($data['stationId']) || $data['sendNotice'] == '' ){
            $this->param_error();
        }

        //时间筛选为空、通知中和通知失败的时候默认搜索两个月的数据
        //防止出现每月一号数据异常
        if( empty( $data['beginDate'] ) ){

            $startTime = date('Y-m-01', strtotime("-1 month"));
            $endTime = date('Y-m-d');

        }

        $mobile = $num = '';

        //包裹编号搜索  2017-05-08
        if ( preg_match( '/^[1][34578]\d{9}$/' , $data['mobile']) )
        {
            $mobile = $data['mobile'];
        }
        else
        {
            $num = $data['mobile'];
        }

        //默认查询所有状态包裹
        if ( $data['parcelStatus'] == '' )
        {
            $data['parcelStatus'] = '-1';
        }

        $parcelService = new \Home\Server\ParcelNoticeResultServer();
        //总数量
        $count = $parcelService->countConditionStorage($data['stationId'],$mobile,$data['beginDate'],$data['parcelStatus'],$data['fCompanyId'], $num, '', $startTime, $endTime , $data['sendNotice'] );

        $page = !empty($data['currentPage']) ? $data['currentPage'] : 1;

        //兼容错误的APP参数
        if( strpos( $data['currentPage'], 'Optional' ) !== False )
        {
            $page = substr( $data['currentPage'], 9, -1 );
        }

        $pageSize = !empty($data['pageSize']) ? $data['pageSize'] : 20;
        $totalPages = ceil($count / $pageSize);

        //查询数据（修补ios分页bug）
        if ($_GET['bmxSource'] == 'ios' && $page == ($totalPages -1))
        {
            $packetList1 =$parcelService->getConditionStorage($data['stationId'],$mobile,$data['beginDate'],$data['parcelStatus'],$page,$pageSize,$data['fCompanyId'], $num , '', $startTime, $endTime , $data['sendNotice'] );
            $packetList2 =$parcelService->getConditionStorage($data['stationId'],$mobile,$data['beginDate'],$data['parcelStatus'],$page+1,$pageSize,$data['fCompanyId'], $num , '', $startTime, $endTime , $data['sendNotice'] );
            $packetList = array_merge($packetList1,$packetList2);
        }
        else
        {
            //查询数据
            $packetList =$parcelService->getConditionStorage($data['stationId'],$mobile,$data['beginDate'],$data['parcelStatus'],$page,$pageSize,$data['fCompanyId'], $num , '', $startTime, $endTime , $data['sendNotice'] );
        }

        //极速包裹总数量（无条件限制）
        $speedNum = $parcelService->countConditionStorage($data['stationId'],'' ,$data['beginDate'],'-1',0, '', '', $startTime, $endTime , '2' );

        //短信内容为空则显示微信通知内容
        foreach ( $packetList as $key=>$value )
        {

            //微信未发送内容为空
            if ( $value['fWeixinStatus'] == '0' )
            {
                $packetList[$key]['fSmsContent'] = '';
            }

            //短信已发送显示短信发送内容
            if ( empty( $value['fSmsContent'] ) && $value['fWeixinStatus'] != '0' )
            {
                $packetList[$key]['fSmsContent'] = "亲，你的快递已到{$packetList[0]['stationName']},请尽快至站点取货。";
            }

            //app端只接受 0.未发送  1.发送成功
            if ( ( $value['fWeixinStatus'] == '2' && $value['fSmsStatus'] == '0' ) || $value['fWeixinStatus'] == '3' || $value['fWeixinStatus'] == '1' )
            {
                //代表显示微信发送图标  app专用  1.微信  0.短信
                $packetList[$key]['fWeixinStatus'] = '1';
            }
            else
            {
                $packetList[$key]['fWeixinStatus'] = '0';
            }

        }

        $result = array(
            'count'             => $speedNum,
            'countNum'          =>$count,
            'parcelInfo'        => $packetList,
            'totlePage'         => $totalPages
        );
        $this->output(true,$result);

    }

    /**
     * @Desc  : 查询极速状态包裹(包括快递站点查询与时间查询)修改版
     * @Author：xushu
     * @Param ：
     * @Time  ：2017/7/13
     * @Update：2017/7/13
     **/
    public function querySpeedParcelBeta()
    {

        $data = I('param.');

        //sendNotice为发送状态  0 全部  1.发送成功  2.草稿箱
        if (empty($data['stationId']) ){
            $this->param_error();
        }


        //时间筛选为空、通知中和通知失败的时候默认搜索两个月的数据
        //防止出现每月一号数据异常
        if( empty( $data['beginDate'] ) ){

            $startTime = date('Y-m-01', strtotime("-1 month"));

        }

        if( empty( $data['endDate'] ) ){

            $endTime = date('Y-m-d');

        }

        $mobile = $num = '';

        //包裹编号搜索  2017-05-08
        if ( preg_match( '/^[1][34578]\d{9}$/' , $data['mobile']) )
        {
            $mobile = $data['mobile'];
        }
        else
        {
            $num = $data['mobile'];
        }

        //默认查询所有状态包裹
        if ( $data['parcelStatus'] == '' )
        {
            $data['parcelStatus'] = '-1';
        }

        $parcelService = new \Home\Server\ParcelNoticeResultServer();
        //总数量
        $count = $parcelService->countConditionStorage($data['stationId'],$mobile,$data['beginDate'],$data['parcelStatus'],0, $num, '', $startTime, $endTime , $data['sendNotice'] ,$data['fCompanyName'] );

        $page = !empty($data['currentPage']) ? $data['currentPage'] : 1;

        //兼容错误的APP参数
        if( strpos( $data['currentPage'], 'Optional' ) !== False )
        {
            $page = substr( $data['currentPage'], 9, -1 );
        }

        $pageSize = !empty($data['pageSize']) ? $data['pageSize'] : 20;
        $totalPages = ceil($count / $pageSize);

        if ($_GET['bmxSource'] == 'ios' && $page == ($totalPages -1))
        {
            $packetList1 =$parcelService->getConditionStorage($data['stationId'],$mobile,$data['beginDate'],$data['parcelStatus'],$page,$pageSize, 0 , $num , '', $startTime, $endTime , $data['sendNotice'] ,$data['fCompanyName']);
            $packetList2 =$parcelService->getConditionStorage($data['stationId'],$mobile,$data['beginDate'],$data['parcelStatus'],$page+1,$pageSize, 0 , $num , '', $startTime, $endTime , $data['sendNotice'] ,$data['fCompanyName']);
            $packetList = array_merge($packetList1,$packetList2);
        }
        else
        {
            //查询数据
            $packetList =$parcelService->getConditionStorage($data['stationId'],$mobile,$data['beginDate'],$data['parcelStatus'],$page,$pageSize,0, $num , '', $startTime, $endTime , $data['sendNotice'] ,$data['fCompanyName']);
        }


        //短信内容为空则显示微信通知内容
        foreach ( $packetList as $key=>$value )
        {

            //微信未发送内容为空
            if ( $value['fWeixinStatus'] == '0' )
            {
                $packetList[$key]['fSmsContent'] = '';
            }

            //短信已发送显示短信发送内容
            if ( empty( $value['fSmsContent'] ) && $value['fWeixinStatus'] != '0' )
            {
                $packetList[$key]['fSmsContent'] = "亲，你的快递已到{$packetList[0]['stationName']},请尽快至站点取货。";
            }

            //app端只接受 0.未发送  1.发送成功
            if ( ( $value['fWeixinStatus'] == '2' && $value['fSmsStatus'] == '0' ) || $value['fWeixinStatus'] == '3' || $value['fWeixinStatus'] == '1' )
            {
                //代表显示微信发送图标  app专用  1.微信  0.短信
                $packetList[$key]['fWeixinStatus'] = '1';
            }
            else
            {
                $packetList[$key]['fWeixinStatus'] = '0';
            }

        }

        $result = array(
            'countNum'          =>$count,
            'parcelInfo'        => $packetList,
            'totlePage'         => $totalPages
        );
        $this->output(true,$result);

    }

    /**
     * @Desc  : 修改极速包裹状态
     * @Author：quyang
     * @Param ：
     * @Time  ：2017/5/9 18:24
     * @Update：2017/5/9
     **/
    public function modifySpeedParcel()
    {

        $param = I('param.');

        if ( empty( $param['stationId'] ) || empty( $param['fParcelId'] ) || empty( $param['tableName'] ) || $param['status'] == '' )
        {
            $this->param_error();
        }

        $SpeedServer = new \Home\Server\SpeedParcelService();

        $update_where = $update_data = [];

        $update_where = [
            'f_station_id'  => $param['stationId'],
            'f_parcel_id'   => $param['fParcelId']
        ];

        $update_data = [
            'f_parcel_status'   => $param['status'],
            'f_last_timestamp'  => time()
        ];

        $parcel = $SpeedServer->updateParcel( $update_where , $update_data , $param['tableName'] );

        if ( $parcel )
        {
            $this->output( true ,array() ,'修改成功' );
        }

        $this->output( false );

    }

    /**
     * @Desc  : 添加备注
     * @Author：quyang
     * @Param ：
     * @Time  ：2017/5/9 19:05
     * @Update：2017/5/9
     **/
    public function parcelCommon()
    {

        $param = I('param.');

        if ( empty( $param['stationId'] ) || empty( $param['fParcelId'] ) || empty( trim( $param['common'] ) ) )
        {
            $this->param_error();
        }

        $Common = new \Home\Server\SpeedParcelCommonService();

        $data = $Common->addCommon( $param['stationId'] , $param['fParcelId'] , $param['common'] );

        if ( $data )
        {
            $this->output( true ,array() ,'添加备注成功' );
        }

        $this->output( false );

    }

    /**
     * @Desc  : 查询极速包裹详情
     * @Author：quyang
     * @Param ：
     * @Time  ：2017/5/10 8:52
     * @Update：2017/5/10
     **/
    public function speedParcelDetail()
    {

        $param = I('param.');

        if ( empty( $param['stationId'] ) || empty( $param['fParcelId'] ) || empty( $param['tableName'] ) )
        {
            $this->param_error();
        }

        $SpeedServer = new \Home\Server\SpeedParcelService();

        //查询包裹详情
        $parcelInfo['list'] = $SpeedServer->queryParcelDetails( $param['fParcelId'] );

        //查询备注内容
        $Common = new \Home\Server\SpeedParcelCommonService();
        $parcelInfo['common'] = $Common->queryParcelCommon( $param['stationId'] , $param['fParcelId'] );

        $this->output( true , $parcelInfo );

    }

}
